/**
 * FC node.js server's main module Author: frogcherry Email:
 * frogcherry@gmail.com created: 2011.09.17
 */
var HOST = "localhost";
var PORT = "80";

var url = require("url");
var qs = require("querystring");
var http = require("http");

var error = require("./ErrorServer.js");
var actionMapper = require("./ActionMapper.fc.cfg.js");

/**
 * 查询映射配置，返回映射的action handle
 * 
 * @param urlObj
 * @returns
 */
function getMappedAction(urlObj) {
	return actionMapper.getMappedAction(urlObj);
}

var server = http
		.createServer(function(req, res) {
			if (req.method === "GET" || req.method === "HEAD"
					|| req.method === "POST") {
				var handler = getMappedAction(url.parse(req.url))
						|| error.notFound;

				res.simpleText = function(code, body) {
					res.writeHead(code, {
						"Content-Type" : "text/plain",
						"Content-Length" : body.length
					});
					res.end(body);
				};

				res.simpleJSON = function(code, obj) {
					var body = new Buffer(JSON.stringify(obj));
					res.writeHead(code, {
						"Content-Type" : "text/json",
						"Content-Length" : body.length
					});
					res.end(body);
				};

				handler(req, res);
			}
		});

server.listen(PORT);

console.log("FC Server is listening port " + PORT);


var ws = require('../libs/ws/ws/server.js');
var sserver = ws.createServer({
	debug : false
});

// Handle WebSocket Requests
sserver.addListener("connection", function(conn) {
	conn.send("Connection: " + conn.id);
	//console.log("###conn### " + conn.id);
	conn.addListener("message", function(message) {
		sserver.broadcast(message);
		//console.log("###get### " + message);
		if (message == "error") {
			conn.emit("error", "test");
		}
	});
});

sserver.addListener("error", function() {
	console.log(Array.prototype.join.call(arguments, ", "));
});

sserver.addListener("disconnected", function(conn) {
	console.log("##" + conn.id + " logout");
	sserver.broadcast("<" + conn.id + "> disconnected");
});

sserver.listen("1923");
console.log("Socket Server is listening port " + 1923);
